extends Panel

@onready var point: ColorRect = $Point
@onready var focus_size: Label = $FocusSize

var current_scene : Node2D
var is_fly : bool
var cancel_range : float = 320.0

func _ready() -> void:
	current_scene = get_tree().current_scene
	current_scene.ball_stop.connect(_on_ball_stop_event)
	hide()

func _gui_input(event: InputEvent) -> void:
	if event is InputEventScreenDrag or (event is InputEventScreenTouch and event.is_pressed()) :
		var mouse_pos = event.position
		var point_size_d_two = (point.size/2.0)
		var new_pos = mouse_pos-point_size_d_two
		point.set_position(point.get_position().lerp(new_pos,0.5))
		var focus_ori = mouse_pos - (size / 2.0)
		var focus = round(focus_ori)
		if focus.length() > (size.x / 2.0) :
			focus = focus.normalized() * (size.x / 2.0)
			point.set_position(focus + (size / 2.0) - point_size_d_two)
		if focus_ori.length() > cancel_range :
			point.color = Color.RED
			focus_size.text = "取消"
		else :
			point.color = Color.WHITE
			focus_size.text = str(round(focus.length()))+"F | "+str(360-round(rad_to_deg(atan2(focus.y,focus.x))+180.0))+str("°")
			current_scene.ball_rotation.emit(-focus.round())
		focus_size.show()
		
	if event is InputEventScreenTouch and not event.is_pressed() :
		#复位
		point.set_position((size/2.0)-(point.size/2.0))
		var mouse_pos = event.position
		var focus = mouse_pos - (size / 2.0)
		if focus.length() > cancel_range :
			point.color = Color.WHITE
			current_scene.ball_emit.emit(Vector2.ZERO)
			return
		if focus.length() < 5.0 or is_fly :
			current_scene.ball_emit.emit(Vector2.ZERO)
			return
		hide()
		if focus.length() > (size.x / 2.0) : focus = focus.normalized() * size.x / 2.0
		current_scene.ball_emit.emit(-focus.round())
		focus_size.hide()
		is_fly = true

func _on_ball_stop_event() -> void :
	is_fly = false
	show()
